package com.kelaite.procurement.service.impl;


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.entity.TPurchaseOrganization;
import com.kelaite.procurement.entity.TPurchaseOrganizationUser;
import com.kelaite.procurement.exception.BusinessException;
import com.kelaite.procurement.repository.PurchaseOrganizationUserRepository;
import com.kelaite.procurement.service.PurchaseOrganizationUserService;

@Service
@Transactional
public class PurchaseOrganizationUserServiceImpl implements
		PurchaseOrganizationUserService {

	@Autowired
	private PurchaseOrganizationUserRepository purchaseOrganizationUserRepository;

	@PersistenceContext
	private EntityManager em;

	@Override
	public TPurchaseOrganizationUser save(TPurchaseOrganizationUser persistence) {

		return this.purchaseOrganizationUserRepository.save(persistence);
	}

	@Override
	public TPurchaseOrganizationUser getObject(Long id) {

		return this.purchaseOrganizationUserRepository.findOne(id);
	}

	@Override
	public List<TPurchaseOrganizationUser> getAll() {

		return this.purchaseOrganizationUserRepository.findAll();
	}

	@Override
	public void deleteByObject(TPurchaseOrganizationUser persistence) {

		this.purchaseOrganizationUserRepository.delete(persistence);
	}

	@Override
	public void deleteByPrimaryKey(Long id) {

		this.purchaseOrganizationUserRepository.delete(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TPurchaseOrganizationUser> getByProperty(String property,
			Object value) {

		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TPurchaseOrganization.class)
				.add(Restrictions.eq(property, value));
		return criteria.list();
	}

	@Override
	public List<TPurchaseOrganizationUser> getListByPurchaseOrganizationId(
			Long purOrganazationId, Integer status) {

		if(null == purOrganazationId){
			throw new BusinessException("purOrganazationId is null. ");
		}
		if(null == status){
			status = Integer.parseInt(Constants.UNDELETED);
		}
		return purchaseOrganizationUserRepository.findByPurchaseOrganizationId(purOrganazationId, status);
	}

}
